package com.coupon.template.schedule;

import com.coupon.template.dao.CouponTemplateDao;
import com.coupon.template.entity.CouponTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 王哲
 * @Contact 1121586359@qq.com
 * @ClassName ScheduleTask.java
 * @create 2023年06月25日 下午5:04
 * @Description 定时任务类--定时清理已过期的优惠券模板
 * @Version V1.0
 */
@Slf4j
@Component
public class ScheduleTask {

    @Resource
    private CouponTemplateDao couponTemplateDao;

    // 定时清理已过期的优惠券模板
    @Scheduled(fixedRate = 60 * 60 * 1000)
    public void offlineCouponTemplate() {
        log.info("Start To Expire CouponTemplate");
        List<CouponTemplate> templateList = couponTemplateDao.findAllByExpired(false);

        if (templateList.isEmpty()) {
            log.info("Done To Expire CouponTemplate But No CouponTemplate Found");
            return;
        }
        ArrayList<CouponTemplate> couponTemplates = new ArrayList<>(templateList.size());
        templateList.forEach(template -> {
            // 根据优惠券模板规则中的过期规则进行判断
            if (template.getRule().getExpiration().getDeadline() < System.currentTimeMillis()) {
                template.setExpired(true);
                couponTemplates.add(template);
            }
        });

        if (!couponTemplates.isEmpty()) {
            log.info("Expired CouponTemplate Num: {}",
                    couponTemplateDao.saveAll(couponTemplates));
        }
        log.info("Done To Expire CouponTemplate");
    }

}
